import pandas as pd
from sklearn.metrics import roc_curve, roc_auc_score
import matplotlib.pyplot as plt

# 加载两个CSV文件
# fileCA = r'D:\code\IBIS\IBIS_RiskEvaluator_CL_v8b_Extracted\CA_risk_5year.csv'  # 替换为标签为1的CSV文件路径
fileCA = r'D:\STUDY\GRADUATE\Dissertation\test3_CArisk.csv'
# fileNCA = r'D:\code\IBIS\IBIS_RiskEvaluator_CL_v8b_Extracted\NCA_risk_5year.csv'  # 替换为标签为0的CSV文件路径
fileNCA = r'D:\STUDY\GRADUATE\Dissertation\test3_NCArisk.csv'
TrueLabel = 'D:\code\IBIS\IBIS_RiskEvaluator_CL_v8b_Extracted\CA_deid_2years.csv'
# 加载预测文件和标签文件
pred_data = pd.concat([pd.read_csv(fileCA), pd.read_csv(fileNCA)], ignore_index=True)  # 替换为预测文件路径
true_labels = pd.read_csv(TrueLabel)  # 替换为存放真实标签的CSV文件路径

# 合并数据，根据id匹配真实标签
# 使用左连接，根据id合并数据，并将缺失标签填充为0
merged_data = pred_data.merge(true_labels, on='id', how='left')  # 使用左连接
merged_data['label'].fillna(0, inplace=True)  # 将缺失标签填充为0
merged_data['label'] = merged_data['label'].astype(int)  # 确保标签为整数

# 提取真实标签和预测概率
y_true = merged_data['label']  # 替换为真实标签的列名
y_pred_proba = merged_data['risk']  # 替换为预测概率的列名

# 计算ROC曲线和AUC
fpr, tpr, thresholds = roc_curve(y_true, y_pred_proba)
auc = roc_auc_score(y_true, y_pred_proba)

# 绘制并保存ROC曲线
plt.figure()
plt.plot(fpr, tpr, color='blue', label=f'ROC curve (AUC = {auc:.2f})')
plt.plot([0, 1], [0, 1], color='grey', linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('5-Year ROC')
plt.legend(loc="lower right")
plt.savefig(r'D:\STUDY\GRADUATE\Dissertation\test3ROC')  # 保存图像
plt.show()

print("AUC值:", auc)
